package com.lau.common.exception;

import com.lau.common.enums.ResultStatusEnum;
import com.lau.common.lang.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

	// 实体校验异常捕获
	@ExceptionHandler(value = MethodArgumentNotValidException.class)
	public Result handler(MethodArgumentNotValidException e) {
		BindingResult result = e.getBindingResult();
		ObjectError objectError = result.getAllErrors().stream().findFirst().get();
		log.error("实体校验异常：----------------{}", objectError.getDefaultMessage());
		return Result.fail(objectError.getDefaultMessage());
	}

	@ExceptionHandler(value = IllegalArgumentException.class)
	public Result handler(IllegalArgumentException e) {
		log.error("Assert异常：----------------{}", e.getMessage());
		return Result.fail(e.getMessage());
	}

	@ExceptionHandler(value = RuntimeException.class)
	public Result handler(RuntimeException e) {
		if(e instanceof DebugException){
			return Result.fail(ResultStatusEnum.VALIDATE.getCode(),e.getMessage());
		}
		return Result.fail(e.getMessage());
	}


}
